package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.dao.UtilMapper;
import com.ld.hpfs.pojo.Exp;
import com.ld.hpfs.pojo.Transport;
import com.ld.hpfs.pojo.Invoice;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.EnterInvoiceService;
import com.ld.hpfs.service.HistoryService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class EnterInvoiceController {
	private static final Logger logger = LoggerFactory.getLogger(EnterInvoiceController.class);

	@Autowired
	private EnterInvoiceService enterInvoiceService;
	@Autowired
    private UtilMapper          utilMapper;
	@Autowired
    private JdbcTemplate jdbcTemplate;
	
	//用于history表
	@Autowired
	private HistoryService historyService;
	/**
	 * 得到系统生成的票据号
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getInvoiceCode")
	public void getVoucherCode(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		try {
			param.put("company_id", session.getAttribute(WebConstants.CURRENT_COMPANY));
			result = enterInvoiceService.getInvoiceCode(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 获取票据类型列表getInvoiceType
	 */
	@RequestMapping(value = "/getInvoiceType")
	public void getInvoiceType(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
			String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
    		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
			param.put("groupId", groupId);
			param.put("language", language);
			result = enterInvoiceService.getInvoiceType(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	/*
	 * 获取票据类型列表getInvoiceType(含导入发票类型)
	 */
	@RequestMapping(value = "/getInvoiceType1")
	public void getInvoiceType1(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
			String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
    		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
			param.put("groupId", groupId);
			param.put("language", language);
			result = enterInvoiceService.getInvoiceType(param);
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> map = new HashMap<String, String>();
			if(language.equals("en")){
			    map.put("text", "Import invoice type"); 
			}else{
			    map.put("text", "导入发票类型"); 
			}
			map.put("value", "ImportType");
			list.add(map);
			for (int i = 0; i < result.size(); i++) {
				HashMap<String, String> map1 = new HashMap<String, String>();
				map1.put("text", (String) result.get(i).get("text"));
				map1.put("value", (String) result.get(i).get("value"));
				list.add(map1);
			}
			String returnMsg = JackJson.fromObjectToJson(list);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	/*
	 * 获取票据类型列表getInvoiceType（含“全部发票”）
	 */
	@RequestMapping(value = "/getInvoiceType2")
	public void getInvoiceType2(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
    		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
    		String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
			param.put("groupId", groupId);
			param.put("language", language);
			result = enterInvoiceService.getInvoiceType2(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 得到票据grid明细信息	
	 */
	@RequestMapping(value = "/getInvoiceDetailList")
	public void getInvoiceDetailList(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		//参数：document_no
		String document_no = request.getParameter("document_no") == "" ? null : (String)request.getParameter("document_no");
		try {
			HashMap<String,Object> param = new HashMap<String,Object>();
			ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
	 			if(!Tools.isEmpty(document_no)){
					param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY));
					param.put("document_no", document_no);
	 			}
				 result = enterInvoiceService.getInvoiceDetailList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}	
	
	/*
	 * 获取票据信息
	 */
	@RequestMapping(value = "/getInvoiceInfo")
	public void getInvoiceInfo(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		String start = request.getParameter("start") == "" ? null: (String)request.getParameter("start");
		String document_no = request.getParameter("document_no") == "" ? null : (String)request.getParameter("document_no");
		try {
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY));
 			if(!Tools.isEmpty(document_no)){
			    param.put("document_no", document_no);
 			}else{
				param.put("pageStart", Integer.parseInt(start));
 			}
 			int count = enterInvoiceService.getInvoiceMainListCount(param);
 			String returnMsg;
 			HashMap<String,Object> obj = new HashMap<String,Object>();
 			if(count != 0){
 				String language = (String) session
 						.getAttribute(WebConstants.CURRENT_LANG);
 				param.put("language", language);
				ArrayList<HashMap<String,Object>> result = enterInvoiceService.getInvoiceMainList(param);
				obj = result.get(0);//当前invoice信息
				obj.put("resultcode", 0);
 				obj.put("count", count);//invoice总数信息
 				if(!Tools.isEmpty(document_no)){
 					obj.put("start", result.get(0).get("rn"));
 				} else {
					obj.put("start", Integer.parseInt(start));//当前第start个invoice
 				}
				returnMsg = JackJson.fromObjectToJson(obj);
 			} else {
 				obj.put("resultcode", 9);
 				obj.put("count", param.get("count"));
 				returnMsg = JackJson.fromObjectToJson(obj);
 			}
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}	
	
	
	/*
	 * 保存票据
	 */
	@RequestMapping(value = "/saveInvoice", method = RequestMethod.POST)	 
	public void saveInvoice(
						//	@RequestParam String[] detail_ids,@RequestParam String[] tax_items,@RequestParam String[] goods_names,@RequestParam String[] specs
//			               ,@RequestParam String[] goods_units,@RequestParam String[] quantitys,@RequestParam String[] price_cures,@RequestParam String[] amount_curs
//			               ,@RequestParam String[] tax_rates,@RequestParam String[] tax_amounts,@RequestParam String[] discount_rates,@RequestParam String[] discount_sums
//			               ,@RequestParam String[] discount_taxs,
 			                @RequestParam String count
 			               ,@RequestParam String itemIds
			               ,Invoice invoice,Exp exp,Transport trans
			               ,HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		
		String[] detail_ids = request.getParameterValues("detail_ids");
		String[] tax_items = request.getParameterValues("tax_items");
		String[] goods_names = request.getParameterValues("goods_names");
		String[] goods_codes = request.getParameterValues("goods_codes");
		String[] specs = request.getParameterValues("specs");
		String[] goods_units = request.getParameterValues("goods_units");
		String[] quantitys = request.getParameterValues("quantitys");
		String[] price_cures = request.getParameterValues("price_cures");
		String[] amount_curs = request.getParameterValues("amount_curs");
		String[] tax_rates = request.getParameterValues("tax_rates");
		String[] tax_amounts = request.getParameterValues("tax_amounts");
		String[] discount_rates = request.getParameterValues("discount_rates");
		String[] discount_sums = request.getParameterValues("discount_sums");
		String[] discount_taxs = request.getParameterValues("discount_taxs");
		
		String[] tp_mileages = request.getParameterValues("tp_mileages");
		String[] goods_categorys = request.getParameterValues("goods_categorys");
		String[] weights = request.getParameterValues("weights");
		String[] weight_units = request.getParameterValues("weight_units");
		String[] weight_discounts = request.getParameterValues("weight_discounts");
		String[] weight_prices = request.getParameterValues("weight_prices");
		String[] volumes = request.getParameterValues("volumes");
		String[] volume_units = request.getParameterValues("volume_units");
		String[] volume_prices = request.getParameterValues("volume_prices");
		String[] fee_amounts = request.getParameterValues("fee_amounts");
		HashMap<String,Object> result = new HashMap<String,Object>();
		HashMap<String,Object> param = new HashMap<String,Object>();
		
		HashMap<String,Object> paramForCount = new HashMap<String,Object>();
		List<HashMap<String,Object>> addList = new ArrayList<HashMap<String,Object>>();
		List<HashMap<String,Object>> updateList = new ArrayList<HashMap<String,Object>>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
 			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
 			int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(companyId));
 			invoice.setCompanyId(companyId);
 			String custName = invoice.getCustom();
 			
 			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
 			if(user == null || session.getAttribute(WebConstants.CURRENT_COMPANY) == null){
 				result.put("resultcode",1);//无用户登录
 			} else {
				int userId = Integer.parseInt(user.getUserId());
				boolean isnew = false;
				if (Tools.isEmpty(invoice.getHeadId())) {
					isnew = true;
				}
 				String cust_code = invoice.getCustCode();
 				String address = invoice.getAddress();
 				String bank=invoice.getAccount();
 				String custTax = invoice.getCustomTax();
 				
 				// 前台取到的客户名称和客户端代码
 				// 客户代码只做备用，现用客户名称去db找有无相同的客户，若果有则选择第一条客户录入
 				paramForCount.put("cust_name", custName);
 				paramForCount.put("custcode", cust_code);
 				paramForCount.put("companyId", Integer.parseInt(companyId));
 				
 				// 检查此用户是否在客户主数据中有记录
 				HashMap<String,Object> custCount =  enterInvoiceService.getCustCount(paramForCount);
 				// 当此客户没有在客户主数据表中不存在则自动添加至客户主数据表
 				if (custCount == null) {
 			         HashMap<String,Object> custForInput = enterInvoiceService.getCustForInput(paramForCount);
 			         if (custForInput != null) {
 			          String custCodeNew = custForInput.get("CUST_CODE").toString();
 			          invoice.setCustCode(custCodeNew);
 			         } else {
 			            HashMap<String,Object> paramForNewCust = new HashMap<String,Object>();
 			            paramForNewCust.put("custName", custName);
 			            paramForNewCust.put("userId", userId);
 			            paramForNewCust.put("groupId", groupId);
 			            paramForNewCust.put("address", address);
 			            paramForNewCust.put("custTax", custTax);
 			            paramForNewCust.put("username", user.getAccount());
 			           paramForNewCust.put("bank", bank);
 			          paramForNewCust.put("invoice", "ImportType");
 			            String custCodeNew = this.getCustCode();
 			            paramForNewCust.put("custCode", custCodeNew);
 			            
 			            invoice.setCustCode(custCodeNew);
 			            enterInvoiceService.insertCustData(paramForNewCust);
 			         }
 				}
 				double discont = 0;
 				for (int i = 0; i < discount_sums.length; i++) {
 					discont = discont + Double.parseDouble(discount_sums[i]);
 				}
 				// 根据计价方式计算金额和税额
 				// 当不含税时：金额=金额-折扣金额
 				if (invoice.getMode() == 0) {
 					invoice.settAmount(String.valueOf((Double.parseDouble(invoice.gettAmount()) - discont)));
 				} 
 				// 当含税时：金额=金额-折扣金额-税额+折扣税额
 				else {
 					double yesAmount = 0;
 					yesAmount = Double.parseDouble(invoice.gettAmount()) - discont - Double.parseDouble(invoice.gettTax());
 					invoice.settAmount(String.valueOf(yesAmount));
 				}
 				// 用于添加history表
				HashMap<String, Object> hist_param = new HashMap<String, Object>();
				int histId = 0;
 				
 				int ret,ret1;
 				invoice.setUpdate_id(Integer.parseInt(user.getUserId()));
 				invoice.setUpdate_name(user.getAccount());
 				param.put("invoiceObj",invoice);
 				param.put("expObj",exp);
 				param.put("transObj", trans);
 				param.put("companyId",companyId);
 				invoice.setGroupId(groupId);
 				if(!Tools.isEmpty(invoice.getHeadId())){//head表
 					
 					// 用于添加history表
 					ArrayList<Integer> headIds = new ArrayList<Integer>();
 					headIds.add(Integer.parseInt(invoice.getHeadId().toString()));
 					hist_param.put("headIds", headIds);
 					hist_param.put("uid", Integer.parseInt(user.getUserId()));
 					hist_param.put("uname", user.getAccount());
 					histId = historyService.addInvoiceHeadHistory(hist_param, 1, false);
 					
 					ret = enterInvoiceService.updateInvoiceMain(param); 					
  				}else{
  					ret = enterInvoiceService.insertInvoiceMain(param);  
  				}
 				
 				for(int i=0;i<price_cures.length;i++){//detail表
					HashMap<String,Object> temp = new HashMap<String,Object>();
					if(Tools.isEmpty(tax_items[i])){
						temp.put("tax_items", "");
					}else{temp.put("tax_items", tax_items[i]);}
					if(Tools.isEmpty(goods_names[i])){
						temp.put("goods_names", "");
					}else{temp.put("goods_names", goods_names[i]);}
					if(Tools.isEmpty(goods_codes[i])){
						temp.put("goods_codes", "");
					}else{temp.put("goods_codes", goods_codes[i]);}
					if(Tools.isEmpty(specs[i])){
						temp.put("specs", "");
					}else{
						temp.put("specs", specs[i]);
					}
					if(Tools.isEmpty(goods_units[i])){
						temp.put("goods_units", "");
					}else{temp.put("goods_units", goods_units[i]);}					
					temp.put("quantitys", quantitys[i]);
					temp.put("price_cures", price_cures[i]);
					temp.put("amount_curs", amount_curs[i]);					
					temp.put("tax_rates", tax_rates[i]);
					temp.put("tax_amounts", tax_amounts[i]);
					temp.put("discount_rates", discount_rates[i]);
					temp.put("discount_sums", discount_sums[i]);
			 		temp.put("discount_taxs", discount_taxs[i]);
					
					if(invoice.getType().equals("T_INV")){
						temp.put("tp_mileages", tp_mileages[i]);
						temp.put("goods_categorys", goods_categorys[i]);
						temp.put("weights", weights[i]);
						temp.put("weight_units", weight_units[i]);
						temp.put("weight_discounts", weight_discounts[i]);
						temp.put("weight_prices", weight_prices[i]);
						temp.put("volumes", volumes[i]);
						temp.put("volume_units", volume_units[i]);
						temp.put("volume_prices", volume_prices[i]);
						temp.put("fee_amounts", fee_amounts[i]);
					}
					if(Tools.isEmpty(detail_ids[i])){
						addList.add(temp);
					}else{
						temp.put("detail_ids", detail_ids[i]);
						updateList.add(temp);
					}
				}
				param.put("addList", addList);//要添加的grid记录
				param.put("updateList", updateList);//要修改的grid记录
			 	param.put("itemIds", itemIds);//要删除的grid记录itemIds(String格式)
				param.put("head_id",invoice.getHeadId());
				param.put("document_no", invoice.getNum());
				param.put("price_way", invoice.getMode());
				
				ret1 = enterInvoiceService.saveInvoiceDetail(param);
				// 判断是否是新增单据
				if (isnew) {
					// 新增票据跑退货，返利存储过程
					runProce(invoice, companyId);
				}
				
				// 用于添加history表
				if(histId != 0){
					hist_param.put("histId", histId);
					historyService.addInvoiceHeadHistory(hist_param, 1, true);
				}
				
 				if(ret>=0 && ret1>=0){
 					int newCount = enterInvoiceService.getInvoiceMainListCount(param);
 					Long start = enterInvoiceService.getStartFromId(param);//通过headId获取当前票据序列号
 						result.put("resultcode", 0);
 			 			result.put("count", newCount);
 			 			result.put("docNo", invoice.getNum());
 			 			result.put("headId", invoice.getHeadId());
 			 			result.put("start", start);
 				} else{
 						result.put("resultcode",9);
 				}
 			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	private void runProce(Invoice invoice, String companyId) {
		HashMap<String,Object> param = new HashMap<String,Object>();
		param.put("companyId", companyId);
		Connection conn = null;
		try {
			CallableStatement proc = null;
			conn = jdbcTemplate.getDataSource().getConnection();
			String custCode = invoice.getCustCode();
			int idHeadId = enterInvoiceService.getMaxHeadId(param);
			// 调用存储过程
			proc = conn.prepareCall("{ call sp_tax_rules_input_main(?,?,?) }");
			proc.setInt(1, Integer.parseInt(companyId));
			proc.setString(2, custCode);
			proc.setInt(3, idHeadId);
			proc.execute();
		} catch (Exception e){
			System.out.println(e);
		}
	}
	
	/**
	 * 删除票据	
	 */
	@RequestMapping(value = "/deleteInvoiceMain")
	public void deleteInvoiceMain(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String headId = request.getParameter("headId") == null ? null : (String)request.getParameter("headId");
		String num = request.getParameter("num") == null ? null : (String)request.getParameter("num");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			param.put("headId", headId);
			param.put("num", num);
			param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY));
			
			// 用于添加history表
			// 若想保留履历，用下面方法添加删除动作
				HashMap<String, Object> hist_param = new HashMap<String, Object>();
				User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
				ArrayList<Integer> headIds = new ArrayList<Integer>();
				headIds.add(Integer.parseInt(headId));
				hist_param.put("headIds", headIds);
				if(user != null){
					hist_param.put("uid", Integer.parseInt(user.getUserId()));
					hist_param.put("uname", user.getAccount());
				}
				historyService.addInvoiceHeadHistory(hist_param, 0, false);
			// 若想删除履历，用下面方法删除该票据的所有履历
//			historyService.deleteInvoiceHistory(Integer.parseInt(headId));
			
			int ret = enterInvoiceService.deleteInvoiceMain(param);
			if(ret == 0){
				result.put("resultcode",0);
			}else{
				result.put("resultcode",9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}	
	
	/*getClientInfoForEnter获取购货单位信息
	 * 
	 */
	@RequestMapping(value = "/getClientInfoForEnter")
	public void getClientInfoForEnter(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
    		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
    		param.put("groupId", groupId);
			result = enterInvoiceService.getClientInfoForEnter(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	 
	
	/*
	 * getGoodsInfoForEnter获取商品信息
	 */
	@RequestMapping(value = "/getGoodsInfoForEnter")
	public void getGoodsInfoForEnter(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
    		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
    		param.put("groupId", groupId);
			result = enterInvoiceService.getGoodsInfoForEnter(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	
	/*
	 * getSellerInfoForEnter获取销方信息
	 */
	@RequestMapping(value = "/getSellerInfoForEnter")
	public void getSellerInfoForEnter(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
    		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
    		param.put("groupId", groupId);
			result = enterInvoiceService.getSellerInfoForEnter(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}


	/*
	 * checkSplitOrMerge 判断票据是否是合并拆分生成的票据
	 */
	@RequestMapping(value = "/checkSplitOrMerge")
	public void checkSplitOrMerge(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
	
		String docs = request.getParameter("docs") == null ? null : (String)request.getParameter("docs");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
	//		param.put("docs", "("+docs+")");
			param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY));
			List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
			String[] Docs = docs.split(",");	
			HashMap<String,String> map= new HashMap<String,String>();
			for(int i=0;i<Docs.length;i++){
				map = new HashMap<String,String>();
				map.put("docNo", Docs[i]);
				list.add(map);
			}
			param.put("list", list);
			int ret = enterInvoiceService.checkSplitOrMerge(param);
			result.put("resultcode",ret);
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	public String getCustCode(){
    	String newCustCode = null;
    	// 取得已cust开头的客户代码
		ArrayList<HashMap<String,Object>> custfornew = enterInvoiceService.getCustCodeForNew();
		// 如果没有一cust开头的code 直接用CUST00000001,否则自动生成code
			if (!(custfornew.size() == 0)) {
			// 首先将所有以cust开头的客户去掉cust 变成数字
			for (int i = 0; i < custfornew.size(); i++) {
				String custcode = custfornew.get(i).get("custCode").toString().toLowerCase();
				custcode = custcode.replace("cust", "");
				int aaa = Integer.parseInt(custcode);
				HashMap<String, Object> paramtemp = new HashMap<String, Object>();
				paramtemp.put("custCode", aaa);
				custfornew.remove(i); 
				custfornew.add(i, paramtemp);
			}
			// 取得最大值
			int kk = 0;
			kk = Integer.parseInt(custfornew.get(0).get("custCode").toString());
			for (int k = 0; k < custfornew.size(); k++) {
				int tmp = Integer.parseInt(custfornew.get(k).get("custCode").toString());
				if (kk < tmp) {
					kk = tmp;
				}
			}
			// 将最大客户按照CUST00000001格式拼成可用的code
			int nextCust = kk + 1;
			String ttt = "00000000" + Integer.toString(nextCust);
			newCustCode = "CUST" + ttt.substring(ttt.length()- 8, ttt.length());
		} else {
			newCustCode = "CUST00000001";
		}
		return newCustCode;
    }
}